//
//  WBNetWorkSessionManager+Extention.swift
//  GitWeibo
//
//  Created by 胡金东 on 2017/5/27.
//  Copyright © 2017年 胡金东. All rights reserved.
//

import Foundation

//MARK: -  封装新浪微博的网络请求方法
extension WBNetWorkSessionManager{
    
    
    
    /// - 加载微博数据字典数组
    /// - Parameters:
    ///   - since_id: 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///   - completion:
    func statusList(since_id:Int64 = 0,max_id:Int64 = 0,  completion:  @escaping (_ list:[[String: Any]]?,_ isSuccess:Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        /// - since_id 和 max_id 转换成字符串 （Int64位是不能转换成Any类型的）
        let params = ["since_id":"\(since_id)",
            "max_id":"\(max_id > 0 ? max_id - 1 : 0)"]
        
        
        tokenRequest(method: .GET, URLString: urlString, parameters: params)
        { ( json, isSuccess ) in
            
            /// - Swift3.1 先用字典去取数据 然后用result as! [[String : Any]]?转成数组
           let result = (json as? [String:Any])? ["statuses"]
            /// - result as! [[String : Any]]?转成数组
           completion( result as! [[String : Any]]?, isSuccess)
            

        }
            
    }
    
    //TODO: - 返回微博未读数据
    func unreadCount(completion:@escaping (_ count: Int) ->())  {
        guard let uid = account.uid else {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid":uid]
        tokenRequest(method: .GET, URLString: urlString, parameters: params){
            (json ,isSuccess) in
            
            let dict = json as? [String:Any]
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
            
            print("微博未读数据\(json)" )
        }
        
        
        
    }
    
}
//MARK: -  加载当前用户信息，用户登录后立即执行
extension WBNetWorkSessionManager{
    func loadUserInfo(completion:@escaping (_ dict:[String:Any])->())  {
        guard  let uid = account.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        tokenRequest(method: .GET, URLString: urlString, parameters: params){
            (json,isSuccess) in
            print(json ?? "用户信息")
            completion((json as? [String:Any]) ?? [:])
        }
        
       
        
    }
}

extension WBNetWorkSessionManager{
    
    func loadAccessToken(code:String,completion:@escaping (Bool) -> ())  {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":WBAppKey,
                     "client_secret":WBAppSecrt,
                     "grant_type":"authorization_code",
                     "code":code,
                     "redirect_uri":WBRedirectURL]
        
        request(method: .POST, URLString: urlString, parameters: params){ (json, isSuccess) in
            
           print(json ?? "")
            
            /// - 直接用字典设置 userAccount的属性 ,[]代表空数组 ,[:]代表空字典
            self.account.yy_modelSet(with: (json as? [String :Any]) ?? [:])
            /// - 加载用户信息
            self.loadUserInfo(completion: { (dict) in
                
                /// - 获取用户昵称和头像
                self.account.yy_modelSet(with: dict)
                /// - 保存模型数据
                self.account.saveAccount()
                /// - 完成回调
                completion(isSuccess)
            })
        }
    
    }
}
